package com.woniu.aimd.config.ai.tools;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class WebSearchTool {

    // SearchAPI 的搜索接口地址
    private static final String SEARCH_API_URL = "https://www.searchapi.io/api/v1/search";

    private final String apiKey = "XHx1F41fe9vNDzj5isxU4LT7";

//    public WebSearchTool(String apiKey) {
//        this.apiKey = apiKey;
//    }

    @Tool(description = "使用百度搜索引擎获取最新的网页信息，适用于需要查找实时数据、新闻、知识或不确定答案的情况")
    public Flux<String> searchWeb(
            @ToolParam(description = "需要搜索的具体问题或关键词，特别是当需要最新信息、实时数据或本地化内容时") String query
            /*,@ToolParam(description = "Search engine to use (baidu/bing/yahoo/yandex), default is google", required = false)
            String engine*/) {
        // baidu
//        if (engine == null || engine.isEmpty()) {
//            engine = "baidu";
//        }
        System.out.println("\n===== AI调用了WebSearchTool.searchWeb()方法 =====");
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("q", query);
        paramMap.put("api_key", apiKey);
        paramMap.put("engine", "baidu");
        return Flux.create(emitter -> {
            try {
                String response = HttpUtil.get(SEARCH_API_URL, paramMap);
                JSONObject jsonObject = JSONUtil.parseObj(response);
                JSONArray organicResults = jsonObject.getJSONArray("organic_results");

                // 先发送标题
                emitter.next("百度搜索结果(前2条):\n\n");

                List<Object> topResults = organicResults.subList(0, Math.min(2, organicResults.size()));
                for (int i = 0; i < topResults.size(); i++) {
                    JSONObject item = (JSONObject) topResults.get(i);

                    // 逐步发送每条结果
                    emitter.next(String.format("%d. %s\n", i + 1, item.getStr("title")));
                    emitter.next(String.format("   链接: %s\n", item.getStr("link")));

                    if (item.containsKey("snippet")) {
                        emitter.next(String.format("   摘要: %s\n", item.getStr("snippet")));
                    }

                    emitter.next("\n"); // 每条结果之间的空行
                }

                emitter.complete();
            } catch (Exception e) {
                emitter.error(new RuntimeException("百度查询出错: " + e.getMessage()));
            }
        });
    }
}


